<?php
/**
 * Controller 基类
 */

namespace backend\controllers;

use app\models\AdminGroup;
use common\models\User;
use yii;
use yii\web\Controller;

class BaseController extends Controller
{
    protected $_adminiId;
    protected $_adminiName;
    protected $_adminiGroupId;
    protected $_adminiPermission;
    protected $pageSize = 20;
    protected $page = 1;
    protected $offset = 0;

    public function init()
    {
        parent::init();
        if (Yii::$app->user->isGuest) {
            //$this->redirect(['/site/login'], '301');
            exit('<script>window.location.href="' . yii\helpers\Url::to(['/site/login']) . '";</script>');
        } else {
            $adminId = Yii::$app->user->id;
            $admin = User::findOne($adminId);
            $group = AdminGroup::findOne($admin['group_id']);
            $this->_adminiId = $adminId;
            $this->_adminiName = $admin->username;
            $this->_adminiGroupId = $group->id;
            $this->_adminiPermission = $group->acl;

            //分页处理
            $this->page = intval(Yii::$app->request->get('page'));
            $perPage = intval(Yii::$app->request->get('per-page'));
            (!$this->page || $this->page <= 0) && $this->page = 1;
            $this->offset = $this->pageSize * ($this->page - 1);
            $perPage && $this->pageSize = $perPage;
        }
    }

    public function beforeAction($action)
    {
        if (parent::beforeAction($action)) {
            $this->_acl();
        }
        return true;
    }

    /**
     * 权限检测
     * 超级用户组跳过检测
     * @param bool $action
     * @param array $params
     */
    protected function _acl($action = false, $params = ['append' => ',site/index'])
    {
        $actionFormat = empty($action) ? strtolower($this->id . '/' . $this->action->id) : strtolower($action);
        $permission = $this->_adminiPermission;
        if ($permission != 'administrator') {
            if (!in_array($actionFormat, explode(',', strtolower($permission) . $params['append']))) {
                if (Yii::$app->request->getIsAjax()) {
                    $var['state'] = 'error';
                    $var['message'] = '当前角色组无权限进行此操作，请联系管理员授权';
                    exit(json_encode($var));
                } else {
                    $this->redirect(['/site/authority'], '301');
                }
            }
        }
    }

    /**
     * @param $message
     * @param string $url
     * @param string $type
     */
    protected function tips($message, $url = 'javascript:history.go(-1);', $type = 'error')
    {
        echo $this->render('/site/tips', ['message' => $message, 'url' => $url, 'type' => $type]);
        exit();
    }
}